import {
  Component,
  ComponentFactoryResolver,
  EventEmitter,
  Input,
  Output,
  QueryList,
  ViewChildren,
  ViewContainerRef
} from '@angular/core';
import {DhlCommonComponent} from '../dhlCommonComponent';
import {ObjectUtil} from '../../../utils/object-util';

@Component({
  selector: 'dhl-tab',
  templateUrl: './dhl-tab.component.html'
})
export class DhlTabComponent extends DhlCommonComponent {

  tabList;

  @Input() activeIndex = 0;
  @Output() changeTab = new EventEmitter();

  @Input() set tabDatas(values) {
    this.tabList = values;
    values.forEach((item, index) => {
      const {component, data} = item;

      if (ObjectUtil.isUndefined(item.showClose)) {
        item.showClose = false;
      }

      if (ObjectUtil.isHaveValue(component)) {
        const componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
        setTimeout(() => {
          const viewRef = this.templateList.filter((p, i) => i == index)[0];
          viewRef.clear();
          const instance = viewRef.createComponent(componentFactory).instance;
          // @ts-ignore
          if (ObjectUtil.isHaveValue(data)) {
            for (const key of Object.keys(data)) {
              const value = data[key];
              instance[key] = value;
            }
          }
        }, 300);
      }
    });
  };

  get tabDatas() {
    return this.tabList;
  }

  @ViewChildren('tabSetDiv', {read: ViewContainerRef}) templateList: QueryList<ViewContainerRef>;


  constructor(private componentFactoryResolver: ComponentFactoryResolver) {
    super();
  }

  selectTab(obj) {
    this.changeTab.emit();
  }


  closeTab(tab, index) {
    this.tabList.splice(index, 1);
  }

}

